package cn.lili.controller.store;

import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.payment.kit.plugin.wechat.WechatV3Api;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.dos.StoreSft;
import cn.lili.modules.store.entity.vos.StoreDetailVO;
import cn.lili.modules.store.entity.vos.StoreSftSearchParams;
import cn.lili.modules.store.entity.vos.StoreSftVO;
import cn.lili.modules.store.service.StoreDetailService;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.store.service.StoreSftService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jfinal.json.FastJson;
import com.jfinal.kit.Ret;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 店铺收付通管理接口
 *
 * @author Bulbasaur
 * @since 2022-08-09 14:55:49
 */
@SuppressWarnings("DuplicatedCode")
@Api(tags = "管理端,店铺收付通管理接口")
@RestController
@RequestMapping("/manager/store/sft")
public class StoreSftManagerController {

    /**
     * 店铺收付通
     */
    @Autowired
    private StoreSftService storeSftService;
    /**
     * 店铺详情
     */
    @Autowired
    private StoreDetailService storeDetailService;
    /**
     * 店铺
     */
    @Autowired
    private StoreService storeService;

    @ApiOperation(value = "获取店铺分页列表")
    @GetMapping("/storeList")
    public ResultMessage<List<Store>> getAllStore(@RequestParam(required = false) String keyword) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.like("store_name", keyword)
                    .or().eq("id", keyword);
        }

        return ResultUtil.data(storeService.list(queryWrapper));
    }

    @ApiOperation(value = "获取店铺收付通分页列表")
    @GetMapping
    public ResultMessage<IPage<StoreSftVO>> getByPage(StoreSftSearchParams entity, PageVO page) {
        return ResultUtil.data(storeSftService.findByConditionPage(entity, page));
    }

    @ApiOperation(value = "获取店铺详情")
    @ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "path", dataType = "String")
    @GetMapping(value = "/store/detail/{storeId}")
    public ResultMessage<StoreDetailVO> shopDetail(@PathVariable String storeId) {
        return ResultUtil.data(storeDetailService.getStoreDetailVO(storeId));
    }

    @ApiOperation(value = "获取店铺收付通详情")
    @ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "path", dataType = "String")
    @GetMapping(value = "/detail/{id}")
    public ResultMessage<StoreSft> detail(@PathVariable String id) {
        return ResultUtil.data(storeSftService.getById(id));
    }

    @ApiOperation(value = "添加店铺收付通二级商户")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage<StoreSft> add(@Valid StoreSft storeSft, Boolean isSubmit) {
        if (storeSftService.getByStoreId(storeSft.getStoreId()) == null) {
            Ret bizContent = FastJson.getJson().parse(storeSft.getBizContent(), Ret.class);
            Ret media = FastJson.getJson().parse(storeSft.getMedia(), Ret.class);
            bizContent.set("out_request_no", storeSft.getStoreId());
            if ("2".equals(bizContent.getStr("organization_type"))) {
                bizContent.set("owner", true);
            }
            storeSft.setBizContent(bizContent.toJson());

            if (BooleanUtils.isNotTrue(isSubmit)) {
                storeSft.setStatus("SUBMIT");
            } else {
                storeSft.setStatus("CHECKING");

                Ret ret = WechatV3Api.applyments(bizContent);

                if (ret.isOk()) {
                    storeSft.setApplymentId(ret.getStr("applyment_id"));
                    storeSft.setApplymentTime(new Date());
                } else {
                    throw new ServiceException("进件失败：" + ret.getStr("msg"));
                }

            }
            boolean result = storeSftService.save(storeSft);
            if (result) {
                return ResultUtil.data(storeSft);
            } else {
                return ResultUtil.error(-1, "执行失败");
            }
        } else {
            return ResultUtil.error(-1, "这个店铺已经进件，不能重复进件");
        }
    }

    @SneakyThrows
    @ApiOperation(value = "编辑店铺收付通二级商户")
    @ApiImplicitParam(name = "id", value = "店铺ID", required = true, paramType = "path", dataType = "String")
    @PutMapping(value = "/edit/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage<StoreSft> edit(@PathVariable String id, @Valid StoreSft storeSft, Boolean isSubmit) {
        StoreSft zft = storeSftService.getById(id);
        if (zft == null) {
            return ResultUtil.error(-1, "执行失败");
        }
        Ret bizContent = FastJson.getJson().parse(storeSft.getBizContent(), Ret.class);

        bizContent.set("out_request_no", storeSft.getStoreId());
        if ("2".equals(bizContent.getStr("organization_type"))) {
            bizContent.set("owner", true);
        }
        zft.setBizContent(bizContent.toJson());
        zft.setMedia(storeSft.getMedia());
        zft.setAttr(storeSft.getAttr());
        if (isSubmit) {

            Ret ret = WechatV3Api.applyments(bizContent);
            zft.setStatus("CHECKING");
            if (ret.isOk()) {
                storeSft.setApplymentId(ret.getStr("applyment_id"));
                storeSft.setApplymentTime(new Date());
            } else {
                throw new ServiceException("进件失败：" + ret.getStr("msg"));
            }

        }
        storeSftService.updateById(zft);
        return ResultUtil.data(zft);
    }

    @ApiOperation(value = "编辑店铺收付通二级商户结算规则")
    @ApiImplicitParam(name = "id", value = "店铺ID", required = true, paramType = "path", dataType = "String")
    @PutMapping(value = "/editSettleRule/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage<StoreSft> editSettleRule(@PathVariable String id, @Valid StoreSft StoreSft) {
        StoreSft zft = storeSftService.getById(id);
        if (zft == null) {
            return ResultUtil.error(-1, "执行失败");
        }
        JSONObject bizContent = JSON.parseObject(StoreSft.getBizContent());
        bizContent.put("alipay_logon_id", bizContent.getString("binding_alipay_logon_id"));

        zft.setBizContent(bizContent.toJSONString());
//        AntMerchantExpandIndirectZftSettlementmodifyModel model=new AntMerchantExpandIndirectZftSettlementmodifyModel();
//        model.setSmid(zft.getSmid());
//        model.set
//        AliPayApi.zftSettlementModify()
        storeSftService.updateById(zft);
        return ResultUtil.data(zft);
    }

    @GetMapping("/getAreaProvinces")
    public ResultMessage<JSONArray> getAreaProvinces() throws NotFoundException, IOException {
        JSONObject data = WechatV3Api.getAreaProvinces();
        return ResultUtil.data(data.getJSONArray("data"));
    }

    @GetMapping("/getCities")
    public ResultMessage<JSONArray> getCities(String provinceCode) throws NotFoundException, IOException {
        JSONObject data = WechatV3Api.getCities(provinceCode);
        return ResultUtil.data(data.getJSONArray("data"));
    }

    @GetMapping("/getPersonalBanks")
    public ResultMessage<JSONArray> getPersonalBanks() throws NotFoundException, IOException {
        return ResultUtil.data(WechatV3Api.getPersonalBanks());
    }

    @GetMapping("/getCorporateBanks")
    public ResultMessage<JSONArray> getCorporateBanks() throws NotFoundException, IOException {
        return ResultUtil.data(WechatV3Api.getCorporateBanks());
    }

    @GetMapping("/getBranches")
    public ResultMessage<JSONObject> getBranches(String bankAliasCode, String cityCode) throws NotFoundException, IOException {
        JSONObject data = WechatV3Api.getBranches(bankAliasCode, cityCode);
        return ResultUtil.data(data);
    }

    @GetMapping("/searchBank")
    public ResultMessage<JSONArray> searchBank(String accountNumber) throws NotFoundException, IOException {
        JSONObject data = WechatV3Api.searchBank(accountNumber);
        return ResultUtil.data(data.getJSONArray("data"));
    }

    @PostMapping("/upload")
    public ResultMessage<String> upload(String url) throws NotFoundException, IOException {
        Ret uploadRet = WechatV3Api.upload(url);
        if (uploadRet.isOk()) {
            return ResultUtil.data(uploadRet.getStr("media_id"));
        }
        return ResultUtil.error(-1, uploadRet.getStr("msg"));
    }
}

